<?php

namespace Eainc\Kingdee;

use Illuminate\Support\ServiceProvider;
use Kingdee\Config;
use Kingdee\Kernel\Client;

/**
 * KingdeeServiceProvider
 */
class KingdeeServiceProvider extends ServiceProvider
{
    protected $key = "kingdee";

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /*
    * Bootstrap the application service
    *
    * @return void
    */
    public function boot()
    {
        if (is_a($this->app, "\\Laravel\\Lumen\\Application")) {
            $this->app->configure($this->key);
        } else {
            $this->publishes([$this->configPath() => \config_path($this->key . ".php")]);
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom($this->configPath(), $this->key);

        $this->app->bind($this->key, function ($app) {
            $config = new Config();
            $config->setBaseUri(\config($this->key . ".base_uri"));
            $config->setAccount(\config($this->key . ".account"));
            $config->setUsername(\config($this->key . ".username"));
            $config->setPassword(\config($this->key . ".password"));
            $config->setLanguage(\config($this->key . ".language"));
            $cacheClient = \config($this->key . ".cache_client");
            if ($cacheClient) {
                $config->setCacheClient($cacheClient);
            }
            $config->setCacheKey(\config($this->key . ".cache_key"));
            $config->setCacheExpire(\config($this->key . ".cache_expire"));
            return new Client($config);
        });
    }

    /**
     * Default config file path
     *
     * @return string
     */
    protected function configPath()
    {
        return __DIR__ . "/config.php";
    }
}
